package com.hzsai.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * @author hzsai
 * @date 2020/1/5 19:41
 * @usage:
 */

@RestController
public class I18nController {

    private static Logger logger = LoggerFactory.getLogger(I18nController.class);

    @Autowired
    private MessageSource messageSource;

    @GetMapping("/i18n/word/")
    public String i18ntest(@RequestParam("word") String word) {

        Locale locale = LocaleContextHolder.getLocale();

        logger.debug("Locale: ", locale.getCountry());
        logger.debug("RequestParam: {}", word);

        String i18nword = "messages." + word;

        String message = messageSource.getMessage(i18nword, null, locale);
        return message;
    }

    @GetMapping("/i18n")
    public String i18ntest(HttpServletRequest request) {

        Cookie[] c = request.getCookies();

        Locale locale = LocaleContextHolder.getLocale();

        logger.debug("Locale: ", locale.getCountry());

        String message = messageSource.getMessage("messages.info", null, locale);
        return message;
    }
}
